package org.example.managementsystem.repository;

import org.example.managementsystem.model.LeaveApproval;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class LeaveApprovalDao {
    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public LeaveApprovalDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<LeaveApproval> findAll() {
        String sql = "SELECT * FROM leave_approval";
        return jdbcTemplate.query(sql, new LeaveApprovalRowMapper());
    }

    public LeaveApproval findById(Long applicationId) {
        String sql = "SELECT * FROM leave_approval WHERE application_id = ?";
        List<LeaveApproval> approvals = jdbcTemplate.query(sql, new LeaveApprovalRowMapper(), applicationId);
        return approvals.isEmpty() ? null : approvals.get(0);
    }

    public void save(LeaveApproval approval) {
        // 检查是否已存在
        if (existsById(approval.getApplicationId())) {
            // 更新现有记录
            String updateSql = "UPDATE leave_approval SET description = ?, is_approved = ? WHERE application_id = ?";
            jdbcTemplate.update(updateSql,
                    approval.getDescription(),
                    approval.getIsApproved(),
                    approval.getApplicationId());
        } else {
            // 插入新记录
            String insertSql = "INSERT INTO leave_approval (application_id, description, is_approved) VALUES (?, ?, ?)";
            jdbcTemplate.update(insertSql,
                    approval.getApplicationId(),
                    approval.getDescription(),
                    approval.getIsApproved());
        }
    }

    public boolean existsById(Long applicationId) {
        String sql = "SELECT COUNT(*) FROM leave_approval WHERE application_id = ?";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class, applicationId);
        return count != null && count > 0;
    }

    public void deleteById(Long applicationId) {
        String sql = "DELETE FROM leave_approval WHERE application_id = ?";
        jdbcTemplate.update(sql, applicationId);
    }

    private static final class LeaveApprovalRowMapper implements RowMapper<LeaveApproval> {
        @Override
        public LeaveApproval mapRow(ResultSet rs, int rowNum) throws SQLException {
            LeaveApproval approval = new LeaveApproval();
            approval.setApplicationId(rs.getLong("application_id"));
            approval.setDescription(rs.getString("description"));
            approval.setIsApproved(rs.getBoolean("is_approved"));
            return approval;
        }
    }
}